﻿using AutoMapper;
using MRSite.AutoMapper.Attributes;
using MRSite.AutoMapper.Extensions;
using MRSite.Common.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.AutoMapper
{
    public class AutoMapperManager
    {
        public static IMapper ShanYuMapper { get; private set; }

        private static readonly ITypeFinder _typeFinder;
        //private static readonly object SyncObj = new object();
        private static IAutoMapperConfiguration autoMapperConfiguration;


        static AutoMapperManager()
        {
            IAssemblyFinder assemblyFinder = new AssemblyFinder();
            _typeFinder = new TypeFinder(assemblyFinder);
            autoMapperConfiguration = new AutoMapperConfiguration();
            CreateMappings();
        }

        private static void CreateMappings()
        {
            Action<IMapperConfigurationExpression> actionConfiguration = configuration =>
            {
                FindMapTypes(configuration);
                foreach (var action in autoMapperConfiguration.ConfigActions)
                {
                    action(configuration);
                }
            };

            Mapper.Initialize(actionConfiguration);
            ShanYuMapper = Mapper.Instance;
        }

        private static void FindMapTypes(IMapperConfigurationExpression configuration)
        {
            var types = _typeFinder.FindByCondition(type =>
            {
                var typeInfos = type.GetTypeInfo();
                return typeInfos.IsDefined(typeof(AutoMapBothAttribute));
            });


            foreach (var item in types)
            {
                configuration.CreateAutoAttributeMaps(item);
            }
        }
    }
}
